package DataBaseQuery;

import DataBaseManager.Row;
import DataType.MyDataType;
import DataType.MyString;

import java.util.ArrayList;

public class MyVarible extends MyExpression {
	static ArrayList<VariableReference> currentVarible = new ArrayList<VariableReference>();
	static public void addCurrentVarible(ArrayList<VariableReference> vars) {
		currentVarible.addAll(vars);
	}
	static public void clearCurrentVarible()
	{
		currentVarible.clear();
	}
	public MyVarible(String name)
	{
		this.name = name;
		type = ExpressionType.VAR;
	}
	public MyVarible(String name,MyDataType val)
	{
		this.name = name;
		value = val;
		type = ExpressionType.VAR;
	}

	@Override
	public MyDataType getValue()
	{
		
		for (VariableReference var : currentVarible) {
			if(var.is(name))
			{
				value = var.value;
				return value;
			}
		}
		
		return null;
	}
	@Override
	public boolean isValid()
	{
		int count=0;
		for (VariableReference var : currentVarible) {
			if(var.is(name))
			{
				count++;
			}
		}
		return count ==1 ;
	}
	@Override
	public MyDataType getValue(RegularView view)
	{
		
		int index = view.getFieldIndex(name);
		if(index == -1)
			return null;
		value = view.fields.get(index).value;
		return value;
	}
	@Override
	public boolean isValid(RegularView view)
	{
		if(name.equals("*"))
			return true;
		int index = view.getFieldIndex(name);
		if(index == -1)
			return false;
		return true;
	}
	public ArrayList<MyDataType> getListValue(RegularView view)
	{
		ArrayList<MyDataType> list = new ArrayList<MyDataType>();
		if(name.equals("*"))
		{
			for (@SuppressWarnings("unused") Row row : view.getRows()) {
				list.add(new MyString());
			}
			return list;
		}
		int index = view.getFieldIndex(name);
		if(index == -1)
			return null;
		for (Row row : view.getRows()) {
			MyDataType val = row.getValue(index);
			
			list.add(val);

		}
		return list;
	}
}
